<?php
require_once("../../Config.php");
require_once("../../Class/ClassFunc.php");
require_once("../../Class/ClassMysql.php");
require_once("../../Class/ClassCheck.php");
require_once("../../Class/ClassResult.php");
require_once("../../Sdk/path_to_sdk/autoload.php");

//json头
header("Content-type: application/json");
// 引入鉴权类
use Qiniu\Auth;
// 引入上传类
use Qiniu\Storage\UploadManager;



session_start();
if(!isset($_SESSION["name"])) {
    exit(Result::wangReturn(1, "未登录"));
}

$uid = (int)$_SESSION["id"];
$uname = $_SESSION["name"];
$uemail = $_SESSION["email"];
$upower = $_SESSION["power"];



if(Check::isEmpty($_POST["content_id"])) {
    exit(Result::wangReturn(1, "参数不足"));
}
$content_id = 0;
if(Check::isNum($_POST["content_id"]) && (int)$_POST["content_id"]>0) {
    $content_id = (int)$_POST["content_id"];
}else {
    exit(Result::wangReturn(1, "参数格式有误"));
}

$db = new DB();
$sql_sel = "SELECT id FROM qilian_contents WHERE user_id={$uid} AND id={$content_id}";
if((int)$db->getRows($sql_sel) == 0) {
    exit(Result::wangReturn(1, "权限不足"));
}

$allRes = array();
foreach($_FILES as $key=>$val) {
    $upName = date("YmdHis").'-'.mt_rand().'-'.$val['name'];
    $upType = $val['type'];

    $ret = putImage($val['tmp_name'], $upName);
    if($ret != false) {
        $sql = "INSERT INTO qilian_attachments(content_id, title, type, akey, hash)".
               " VALUES({$content_id}, '{$upName}', '{$upType}', '{$ret['key']}', '{$ret['hash']}')";
        $id = 0;
        if($id=$db->insert($sql)) {
            array_push($allRes, array(
                "id"=>$id,
                "content_id"=>$content_id,
                "title"=>CDN.$upName,
                "type"=>$upType,
                "url"=>CDN.$upName,
                "alt"=>"图片",
                "href"=>CDN.$upName,
                "akey"=>$ret['key'],
                "hash"=>$ret['hash']
            ));
        }
    }
}


exit(Result::wangReturn(0, "提交成功", $allRes));



function putImage($localPath, $name) {
    // 需要填写你的 Access Key 和 Secret Key
    $accessKey = ACCESS_KEY;
    $secretKey = SECRET_KEY;
    $bucket = BUCKET;

    // 构建鉴权对象
    $auth = new Auth($accessKey, $secretKey);
    // 生成上传 Token
    $token = $auth->uploadToken($bucket);
    // 要上传文件的本地路径
    $filePath = $localPath;
    // 上传到存储后保存的文件名
    $key = $name;
    // 初始化 UploadManager 对象并进行文件的上传。
    $uploadMgr = new UploadManager();
    // 调用 UploadManager 的 putFile 方法进行文件的上传。
    list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);

    if ($err !== null) {
        return false;
    } else {
        return $ret;
    }
}




?>